﻿//SmsLogListener.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Logging
{
	using System;

	using Google.GData.Calendar;
	using Google.GData.Client;
	using Google.GData.Extensions;

	/// <summary>
	/// Логгер, отсылающий данные через SMS с помощью Google Calendar. 
	/// </summary>
	public class SmsLogListener : LogListener
	{
		private readonly Uri _postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
		private readonly CalendarService _service;

		/// <summary>
		/// Создать <see cref="SmsLogListener"/>.
		/// </summary>
		/// <param name="login">Логин в Google.</param>
		/// <param name="password">Пароль в Google.</param>
		public SmsLogListener(string login, string password)
			: this(login, password, "StockSharp")
		{
		}

		/// <summary>
		/// Создать <see cref="SmsLogListener"/>.
		/// </summary>
		/// <param name="login">Логин в Google.</param>
		/// <param name="password">Пароль в Google.</param>
		/// <param name="appName">Название сервиса.</param>
		public SmsLogListener(string login, string password, string appName)
		{
			_service = new CalendarService(appName);
			_service.setUserCredentials(login, password);
		}

		/// <summary>
		/// Создать Google сообщение.
		/// </summary>
		/// <param name="message">Отладочное сообщение.</param>
		/// <returns>Google сообщение.</returns>
		protected virtual EventEntry CreateGoogleEntry(LogMessage message)
		{
			if (message == null)
				throw new ArgumentNullException("message");

			var entry = new EventEntry
			{
				Service = _service,
				Title = { Text = message.Source.Name + " " + message.Level },
				Content = { Content = message.Message },
			};

			entry.Authors.Add(new AtomPerson(AtomPersonType.Author));
			entry.Times.Add(new When(DateTime.Now.AddMinutes(2), DateTime.Now.AddMinutes(3)));

			entry.Reminder = new Reminder
			{
				Minutes = 1,
				Method = Reminder.ReminderMethod.sms
			};

			return entry;
		}

		/// <summary>
		/// Записать сообщение.
		/// </summary>
		/// <param name="message">Отладочное сообщение.</param>
		protected override void OnWriteMessage(LogMessage message)
		{
			_service.Insert(_postUri, CreateGoogleEntry(message));
		}
	}
}